//
//  AIGirlMessagePremiumView.swift
//  AIGirl
//
//  Created by Rae on 2024/1/2.
//

import UIKit
import SwiftEntryKit

class AIGirlMessagePremiumView: UIView, AnimationProtocol, AnimationDelegate, UorInXNetworkProtocol {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: .screenHeight)
    }
    
    func animationContainerViewStyle() -> AnimationViewStyle {
        .bottom
    }
    
    private lazy var dismissBtn = c_make_ex(UIButton.self)
        .bgColor(.black.alpha(0.5)).end()
    private lazy var bgView = c_make_ex(UIView.self)
        .bgColor("#1B1325").corner(30, corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner]).end()
    private lazy var titleImageView = c_make_ex(UIButton.self)
        .image("AIGirl_Message_premiumTitleV").end()
    private lazy var desLabel = c_make_ex(UILabel.self)
        .text("status for double intimacy points.").alignment(.center)
        .font(15.font_medium).color("#E2D2FC").end()
    private lazy var bestBgView = c_make_ex(UIImageView.self)
        .image("AIGirl_Home_bestBg").mode(.scaleAspectFill).end()
    private lazy var bestImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Home_bestDeal").mode(.scaleAspectFill).end()
    private lazy var diamondImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Home_purpleDiamond").mode(.scaleAspectFill).end()
    private lazy var diamondLabel = c_make_ex(UILabel.self)
        .color(.white).font(20.font_bold).end()
    private lazy var joinButton = c_make_ex(UIButton.self)
        .bgImage("AIGirl_Home_bestButton")
        .color("#643208").font(16.font_bold).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var rechargeList: [AIGirlHomeItemModel] = []
    var model: AIGirlHomeModel?{
        didSet{
            guard let md = model else { return }
            var dataArr = md.rechargeList
            dataArr.sort{$0.sortTop < $1.sortTop}
            rechargeList = dataArr
            diamondLabel.text = md.activityRecharge.coin
            joinButton.setTitle("$ " + md.activityRecharge.price, for: .normal)
            collectionView.reloadData()
        }

    }
    
    var dismissClosure: (() -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
//        backgroundColor = .black.alpha(0.5)
//        layer.cornerRadius = 30
//        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        
        loadData()
        subviews{
            dismissBtn
            bgView.subviews{
                titleImageView
                desLabel
                bestBgView.subviews{
                    bestImageView
                    diamondImageView
                    diamondLabel
                    joinButton
                }
                collectionView
            }
        }
        
        bgView.top(.screenHeight - 615.0).leading(0).trailing(0).bottom(0)
        dismissBtn.top(0).leading(0).trailing(0)
        dismissBtn.Bottom == bgView.Top + 30
        titleImageView.top(45).centerHorizontally()
        desLabel.top(65).centerHorizontally()
        bestBgView.leading(10).trailing(10).height(150)
        bestBgView.Top == desLabel.Bottom + 15
        bestImageView.leading(0).top(19).width(148).height(33)
        diamondImageView.leading(48).top(66).size(30)
        diamondLabel.Leading == diamondImageView.Trailing + 5
        diamondLabel.CenterY == diamondImageView.CenterY
        joinButton.leading(27).width(110).height(33)
        joinButton.Top == diamondImageView.Bottom + 10
        collectionView.leading(0).trailing(0).top(265).bottom(0)

        let w = (.screenWidth - 35) / 2
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 10.0, bottom: 0, right: 10.0)
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: w, height: 180.0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlDiamondItem.self, forCellWithReuseIdentifier: AIGirlDiamondItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        bgView.isUserInteractionEnabled = true
        dismissBtn.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
        titleImageView.addTarget(self, action: #selector(clickPremiumBtn), for: .touchUpInside)
        let tapG = UITapGestureRecognizer(target: self, action: #selector(buyCoin))
//        bgView.isUserInteractionEnabled = true
        
        bestBgView.isUserInteractionEnabled = true
        bestBgView.addGestureRecognizer(tapG)
    }
    
    @objc private func clickPremiumBtn(){
        
        if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
            GlobalTool.showAlreadyVipInfoPage()
        }else{
            GlobalTool.showVipInfoPage()
        }
    }
    
    @objc private func buyCoin(){
        
        guard let md = model?.activityRecharge else { return }
        purchaseTool.purchaseProduct(productCode: md.code, productId: md.id)
    }
    
    @objc private func clickDismissButton(){
        animation.animation(dismiss: self){
            self.dismissClosure?()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

   private func loadData() {
        //商品信息
        request.start(.rechargeList(needActivityRechargeTypes: "recommendRecharge"),type: AIGirlHomeModel.self,isLoading: false) { result in
            if result.isSuccessful, let md = result.model {
                self.model = md
            }
        }
    }
    
}

extension AIGirlMessagePremiumView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return rechargeList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlDiamondItem.description(), for: indexPath) as? AIGirlDiamondItem else { return UICollectionViewCell() }
        var model = rechargeList[indexPath.row]
        model.index = indexPath.row
        item.model = model
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let model = rechargeList[indexPath.row]
        purchaseTool.purchaseProduct(productCode: model.code, productId: model.id)
    }
}
